<?php
	ini_set('display_errors', 'off');
	//error_reporting(E_STRICT);
	class WordsList extends Common{
		private $db;
		private $tables = '';
		private $oldData = array();
		//public $act = "add";
		public $where = "";
		public $str = "";
		public $optParam = 'word,version,sen_level as level,sen_type as type,siteid as site,systype as system,iswhitelist,create_time as createtime';//接口操作的参数串
		public $addKey = "cdelSenword!@#$%";
		public $sql;
		
		function __construct(){
			parent::__construct();
			$this->db = new DbModel('mysql');		    
		}

		function query($sql){
			return $this->db->query($sql);
		}
	
		//获取数据库中数据条数
		public function getWordNum($sql){
			print($sql);
			//$sql = "select count(id) as num from words where iswhitelist = {$iswhitelist}";
			if($res = $this->db->find($sql)){
				$num = $res['num'];
				return $num;
			}else{
				return false;
			}
		}
		//获取全部的黑名单
		public function getAllBlack(){
			print("invoke getAllBlack");
			$sql = "select id,word,version,type,sisteid,systype,create_time,update_time from words order by update_time desc";
			echo "sql is =====".$sql;
			print ("sql is =====");
			return $sql;
			if ($res = $this->db->findAll($sql)) {
				$blackwords = $res;
				return $blackwords;
			}else{
				return false;
			}
		}
		//数字编号转换为字符串
		public function typeToStr($no,$genre){
			$wordsarr = getConfig("$genre");

			foreach ($wordsarr as $key => $value) {
				if (intval($no) == intval($key)) {
					return $value;
				}
			}
			return false;
		}
		//查询修改数据信息
		public function getEditData($editDataId){
			// $editDataId = $editDataParam['id'];
			$this->where = "id = {$editDataId}";
			$Msql = "select * from words where {$this->where}";
			//echo $Msql;
			$getEditData = $this->db->find($Msql);
			unset($Msql);
			return $getEditData['word'];
		}
		//分页显示数据
		public function getPageData($parameterArr,$offset = '',$limit = '',$iswhitelist = 0){
			//拼接字符串
			$where = " iswhitelist = {$iswhitelist} ";
			
			$jointData = $this->joint($parameterArr);
			$where .= $jointData['where'];
			echo "-------where = {$where}";
			//sql语句
			$data_sql = "select id,word,sen_level,version,sen_type,sisteid,systype,create_time,update_time from words where {$where} order by update_time desc";
			$num_sql = "select count(id) as num from words where {$where}";

			$resnum = $this->getWordNum($num_sql);
			//return $resnum;
			
			if($limit !=0)
			{
				$data_sql .= " limit $offset,$limit";				
			}	
			
			$resdata = $this->db->findAll($data_sql);
			
			$res['data'] = $resdata;
			$res['num'] = $resnum;
			$res['str'] = $jointData['str'];
			if($res)
			{
				return $res;
			}
			else
			{
				return false;
			}
			
		}
		//拼接where条件
		public function joint($parameterArr = array()){
			print("in joint");
			if (empty($parameterArr)){
				$this->where = " and 1 = 1";
			}else {
				if (isset($parameterArr['id'])) {
					$this->where .= " and id = {$parameterArr['id']}";
				}
				if (isset($parameterArr['word']) && !empty($parameterArr['word'])) {
					# code...
					$this->str.="wordname={$parameterArr['word']}&";
					$this->where .= " and word like '%{$parameterArr['word']}%'";
				}
				if (isset($parameterArr['version']) && !empty($parameterArr['version'])) {
					# code...
					$this->str.="version={$parameterArr['version']}&";
					$this->where .= " and version like '%{$parameterArr['version']}%'";
				}
				if (@$parameterArr['sen_level'] != -1 && isset($parameterArr['sen_level'])&& !empty($parameterArr['sen_level'])) {
					# code...
					$this->str.="sen_level={$parameterArr['sen_level']}&";
					$this->where .= " and sen_level = {$parameterArr['sen_level']}";
				}
				if (@$parameterArr['sen_type'] != -1 && isset($parameterArr['sen_type'])&& !empty($parameterArr['sen_type'])) {
					# code...
					$this->str.="sen_type={$parameterArr['sen_type']}&";
					$this->where .= " and sen_type = {$parameterArr['sen_type']}";
				}
				if (@$parameterArr['sisteid'] != -1 && isset($parameterArr['sisteid'])&& !empty($parameterArr['sisteid'])) {
					# code...
					$this->str.="sisteid={$parameterArr['sisteid']}&";
					$this->where .= " and sisteid = {$parameterArr['sisteid']}" ;
				}
				if (@$parameterArr['systype'] !=-1 && isset($parameterArr['systype'])&& !empty($parameterArr['systype'])) {
					# code...
					$this->str.="systype={$parameterArr['systype']}&";
					$this->where .= " and systype = {$parameterArr['systype']}";
				}
			}
			$jointArr['where'] = $this->where;
			unset($this->where);
			$jointArr['str'] = $this->str;
			unset($this->str);
			return $jointArr;
			
		}
		/*
		*生成批量导入的参数数据
		 */
		public function batchParam($batchData = array()){
			$batchParamArr = array();
			$batchParamArr['word'] = $batchData['word'];
			$batchParamArr['version'] = $batchData['version'];
			$batchParamArr['type'] = $batchData['sen_type'];
			$batchParamArr['site'] = $batchData['sisteid'];
			$batchParamArr['system'] = $batchData['systype'];
			$batchParamArr['iswhitelist'] = "0";
			$batchParamArr['level'] = $batchData['sen_level'];
			$batchParamArr['createtime'] = date("Y-m-d H:i:s",time());
			$batchParamArr['act'] = "add";

			return $batchParamArr;
		}
		/**
		*	批量导入
		*/
		public function batchInput($word_arr = array())
		{

			if(!empty($word_arr))
			{
				foreach($word_arr as $word)
				{	

					$batchParamArr = $this->batchParam($word);
// 					//读取配置文件，获取系统配置
// 					$configData = getConfig('systype');
// 					//将数字标识转换为字符标识
// 					foreach ($configData as $k=>$v){
// 						if ($k == $batchParamArr['system']){
// 							$batchParamArr['system'] = $v;
// 						}
// 					}
					
					switch ($batchParamArr['system']){
						case 0:
							$batchParamArr['system'] = "通用";
							break;
						case 1:
							$batchParamArr['system'] = "bbs";
							break;
						case 2:
							$batchParamArr['system'] = "cms";
							break;
					}
					
					$Interface_status = $this->curldata($batchParamArr);
					if ($Interface_status == 0){
						$res = $this->inputOne($word['word'],$word['version'],$word['sen_level'],$word['sen_type'],$word['sisteid'],$word['systype'],$word['iswhitelist']);
						//echo $res;
						// return $res;
						// exit;
						if($res == 1)
						{
							echo $word['word']."---添加成功！<br>";
						}
						elseif($res == 0)
						{
							echo $word['word']."---<font color='red'>添加失败！</font><br>";
						}
						elseif ($res == 2) {
							echo $word['word']."---<font color='red'>添加失败！原因：该数据已添加！</font><br>";
						}
					}else {
						echo "请求filter.chnedu.com失败";
						exit;
					}
				}
			}
			return false;		
		}


		private function inputOne($wordname="",$version="",$sen_level="",$sen_type="",$sisteid="",$systype="",$iswhitelist)
		{
			
			if(($this->ps_exist($wordname,$sisteid)))
			{
				return 2;
			}
			
			$sql = "insert into words (word,version,sen_level,sen_type,sisteid,systype,iswhitelist,create_time,update_time)values('{$wordname}','{$version}','{$sen_level}',$sen_type,$sisteid,$systype,$iswhitelist,now(),now())";
			//return $sql;
			if($this->db->execute($sql))
			{
				// $record = '添加了一条关键词记录：'.$wordname;
				// Operatelog::add($this->db,$record);						
				return 1;
			}	
			return 0;		
		}

		/**
		*	
		*/
		function ps_exist($wordname,$sisteid)
		{
			$sql = "select id from words where binary word = '{$wordname}'";
			if ($sisteid == 0) {
		    	//$sql = "select `word` from words where `word` in ($seaStr)";
		    }else{
		    	$sql .= " and (`sisteid` = {$sisteid} or `sisteid` = 0)";
		    }
			
			//return $sql;
			// $rs = $this->db->find($sql);
			// return $rs;
			if($rs = $this->db->find($sql))
			{
				return true;
			}
			return false;
		}

		//检验关键词是否唯一
		public function getIdByName($wordname){
			$seaArr = explode('|',$wordname);

		    $seaStr = "'".implode("','",$seaArr)."'";
			$sql = "select word from words where word in ($seaStr)";
			
			$findData = $this->db->findAll($sql);
			foreach ($findData as $key => $value) {
				$result[] = $value["word"];
			}
			
			@$res = array_intersect($seaArr, $result);
			return $res;
		}
		//检验关键词是否唯一
		public function getIdByNameSite($wordname,$sisteid){
			$seaArr = explode('|',$wordname);

		    $seaStr = "'".implode("','",$seaArr)."'";
		    $sql = "select `word` from words where `word` in ($seaStr)";
		    if ($sisteid == 0) {
		    	//$sql = "select `word` from words where `word` in ($seaStr)";
		    }else{
		    	$sql .= " and (`sisteid` = {$sisteid} or `sisteid` = 0)";
		    }
			
			// echo $sql;
			$findData = $this->db->findAll($sql);
			foreach ($findData as $key => $value) {
				$result[] = $value["word"];
			}
			
			@$res = array_intersect($seaArr, $result);
			return $res;
		}
		//检测编辑关键词唯一性
		public function checkEditWord($wordname){
			$sql = "select word from words where word=$wordname";
		}
		/*
		*添加数据参数拼接
		*@param  $PostData  array  原始数据
		*@param  $act  string  操作标识   add  写入返回数组
		*return  $res  array  数据和MySQL的sql
		 */
		function addParam($PostData = array(),$act = ""){
			$words = array();
			
			$wordarr = explode('|',$PostData['word']);

			$sql = "insert into {$PostData['table']}(word,version,sen_level,sen_type,sisteid,systype,iswhitelist,create_time,update_time) values";
			foreach ($wordarr as $key => $value) {
				if ($key == 0) {
					$sql .= "('{$value}','{$PostData['version']}',{$PostData['sen_level']},{$PostData['sen_type']},{$PostData['sisteid']},{$PostData['systype']},{$PostData['iswhitelist']},now(),now())";
		
				}else{
					$sql .= ",('{$value}','{$PostData['version']}',{$PostData['sen_level']},{$PostData['sen_type']},{$PostData['sisteid']},{$PostData['systype']},{$PostData['iswhitelist']},now(),now())";
				}
				$words[$key]['word'] = $value;
				$words[$key]['version'] = $PostData['version'];
				$words[$key]['type'] = $PostData['sen_type'];
				$words[$key]['site'] = $PostData['sisteid'];
				$words[$key]['system'] = $PostData['systype'];
				$words[$key]['iswhitelist'] = $PostData['iswhitelist'];
				$words[$key]['level'] = $PostData['sen_level'];
				$words[$key]['create_time'] = date("Y-m-d H:i:s",time());
				$words[$key]['act'] = $act;
			}
			$res['word'] = $words;
			$res['sql'] = $sql;
			unset($words);
			return $res;
		}
		/*
		*接口操作
		*@param  $paramData  array  操作的数据数组
		*@param  $act  string  操作标识
		*return true/false  bool  是否成功标识
		 */
		public function curldata($paramData = array(),$act = ""){
			
			//拼接json串,匹配相关的json参数格式
			if ($act == "add") {
				$jsonstr = '{"words":'.json_encode($paramData).'}';
			}else {
				$jsonstr = '{"words":['.json_encode($paramData).']}';
			}
			// echo $jsonstr;
			// exit;
			$time = date("Y-m-d H:i:s",time());
			$pkey = md5($this->addKey.$time);
			$putdata = array();
			$putdata = array(
				"jsonstr" => $jsonstr,
				"pkey" => $pkey,
				"time" => $time,
			);
			//参数编码为URL请求字符串
			$str = "";
			$str .= http_build_query($putdata);
			
			//curl  post提交数据
			$curl = getConfig('putdata_url');
			// $ch = curl_init('http://filter.chnedu.com/v2/putdata');
			$ch = curl_init($curl);
			//post方式
			curl_setopt($ch,CURLOPT_POST,1);
			//post数据数组
			curl_setopt($ch, CURLOPT_POSTFIELDS, $str);

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			//执行curl并关闭
			$curldata = curl_exec($ch);
			//exit;
			curl_close($ch);
			//json转为数组
			$result = json_decode($curldata,true);
			//释放数组
			unset($configData);
			unset($paramData);
			return $result['returnCode'];
		}

		/*
		*删除数据
		*@param $wordid string 删除数据的id
		*@param $act string 操作类别
		*return  true/false  bool  是否成功标识
		 */
		public function del($wordid = "",$act = ""){
			//通过id查询相关参数的sql，用于接口删除
			$sql = "select word,version,sen_level as level,sen_type as type,sisteid as site,systype as system,iswhitelist,create_time as createtime from words where id = $wordid";
			//MySQL删除sql
			$Msql = "delete from words where id = $wordid";
			//查询删除数据信息
			$delData = $this->db->find($sql);
			$delData['act'] = "del";

// 			//读取配置文件，获取系统配置
// 			$configData = getConfig('systype');
// 			//将数字标识转换为字符标识
// 			foreach ($configData as $k=>$v){
// 				if ($k == $delData['system']){
// 					$delData['system'] = $v;
// 				}
// 			}
			
			switch ($delData['system']){
				case 0:
					$delData['system'] = "通用";
					break;
				case 1:
					$delData['system'] = "bbs";
					break;
				case 2:
					$delData['system'] = "cms";
					break;
			}
			
			//调用curldata 方法   获取接口操作标识符
			$Interface_status = $this->curldata($delData,$act);
			//$Interface_status = 0;
			unset($delData);
			if($Interface_status == 0){
				if ($res= $this->db->execute($Msql)) {
					return true;
				}
			}else {
				return false;
			}
		}
		
		/*
		*修改数据
		*@param  $table string  操作的表名
		*@param  $editData array 修改的参数数组
		*@param  $act   string  操作的标识   modify
		*@param  $oldword  string  修改前的关键词
		*return  true/false  bool  是否成功标识
		 */
		public function edit($table = "",$editData = array(), $act = "", $oldword = ""){
			//参数所需参数
			$putdata = array();
			$putdata['word'] = $oldword;
			$putdata['newWord'] = $editData['word'];
			$putdata['version'] = $editData['version'];
			$putdata['type'] = $editData['sen_type'];
			$putdata['site'] = $editData['sisteid'];
			$putdata['system'] = $editData['systype'];
			$putdata['iswhitelist'] = "0";
			$putdata['level'] = $editData['sen_level'];
			$putdata['createtime'] = date("Y-m-d H:i:s",time());
			$putdata['act'] = $act;

			//MySQL操作的sql
			$Msql = "update {$table} set word = '{$editData['word']}',version = '{$editData['version']}',sen_level = '{$editData['sen_level']}',sen_type = {$editData['sen_type']},sisteid = {$editData['sisteid']},systype = {$editData['systype']},update_time = now() where id = {$editData['id']}";

// 			//读取配置文件，获取系统配置
// 			$configData = getConfig('systype');
// 			//将数字标识转换为字符标识
// 			foreach ($configData as $k=>$v){
// 				if ($k == $putdata['system']){
// 					$putdata['system'] = $v;
// 				}
// 			}

			switch ($putdata['system']){
				case 0:
					$putdata['system'] = "通用";
					break;
				case 1:
					$putdata['system'] = "bbs";
					break;
				case 2:
					$putdata['system'] = "cms";
					break;
			}
			//调用curldata 方法   获取接口操作标识符
			$Interface_status = $this->curldata($putdata,$act);
			//$Interface_status = 0;
			// var_dump($Interface_status);
			// exit;
			unset($putdata);
			if($Interface_status == 0){
				if (@$this->db->execute($Msql)) {
					return true;
				}else{
					return false;
				}
			}else {
				return false;
			}
		}
		/*
		*添加数据
		*@param $data 添加的数据
		*@param $act  操作标识  add
		*return true false  是否成功
		 */
		public function	add($data = array(),$act = ""){
			//读取配置中接口地址
			$url = getConfig('putdata_url');
			//调用方法获取添加数据参数
			$param = $this->addParam($data,$act);
		
			
			//Mysql 的sql 
			$Msql = $param['sql'];
			$word = $param['word'];
			//获取配置文件中的数据，将数字标识转为字符标识
			$configData = getConfig('systype');
			foreach ($configData as $k=>$v){
				foreach ($word as $wk=>&$wv){
					if($wv['system'] == $k){
						$wv['system'] = $v;
					}	
				}
				unset($wv);
			}
			
			//调取curl传输数据的方法  获得标识
			$Interface_status = $this->curldata($word,$act);
			//$Interface_status = 0;
			if ($Interface_status == 0){
				if ($res = $this->db->execute($Msql)) {
					return true;
				}else{
					return false;
				}
			}else {
				return false;
			}
		}

	}

?>
